<template>
  <n-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    size="small"
    label-placement="left"
    label-width="80px">
    <n-grid :cols="12" :x-gap="24">
      <n-form-item-gi :span="12" label="连接名称" path="name">
        <n-input v-model:value="formData.name" placeholder="name" />
      </n-form-item-gi>
      <n-form-item-gi :span="7" label="主机" path="host">
        <n-input v-model:value="formData.host" placeholder="host" />
      </n-form-item-gi>
      <n-form-item-gi :span="5" label="端口" path="port" label-width="60px">
        <n-input
          v-model:value="formData.port"
          placeholder="port"
          :allow-input="(value) => !value || /^\d+$/.test(value)" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="用户名" path="username">
        <n-input v-model:value="formData.username" placeholder="username" />
      </n-form-item-gi>
      <n-form-item-gi :span="12" label="密码" path="password">
        <n-input
          v-model:value="formData.password"
          placeholder="password"
          type="password" />
      </n-form-item-gi>
    </n-grid>
  </n-form>
</template>

<script lang="ts" setup>
import type { FormRules, FormInst } from "naive-ui";
import { getDatabases } from "@/api";
import { context } from "@/storage/context";

const props = defineProps<{ data: DataSourceInfo }>();

const originName = props.data.name;
const formData = ref<DataSourceInfo>(props.data);
const formRules: FormRules = {
  name: [
    { required: true, message: "请输入连接名称" },
    {
      validator: (_, name: string) => {
        if (name === originName) return true;
        const dataSourceConf = context.getDataSourceConfig();
        if (Object.keys(dataSourceConf).includes(name)) {
          return new Error("连接名称已存在");
        }
      },
    },
  ],
  host: { required: true, message: "请输入主机地址" },
  port: { required: true, message: "请输入端口" },
  username: { required: true, message: "请输入用户名" },
  password: { required: true, message: "请输入密码" },
};

const formRef = ref<FormInst>();
const handleConnect = async () => {
  await formRef.value?.validate();
  const { data } = await getDatabases(formData.value);
  return { form: formData.value, data };
};

defineExpose({
  handleConnect,
});
</script>
